package com.sca.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/*
* 实现该类就能对我们的sentinel监控异常进行数据返回的设置
* */
@Component
public class DefaultBlackException implements BlockExceptionHandler {


    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        PrintWriter pw=response.getWriter();
        Map<String,Object> map=new HashMap<>();
        if(e instanceof DegradeException){//降级、熔断
            map.put("status",601);
            map.put("message", "服务被熔断了!");
        }else if(e instanceof FlowException){
            map.put("status",602);
            map.put("message", "服务被限流了!");
        }else{
            map.put("status",603);
            map.put("message", "请保持良好信誉，不然要被打四的");
        }
        //将map对象转换为json格式字符串
        String jsonStr=new ObjectMapper().writeValueAsString(map);
        pw.println(jsonStr);
        pw.flush();
    }


    }

